<?php

namespace doujunyu\utility;

use PhpOffice\PhpSpreadsheet\Spreadsheet;
use think\Exception;


class SelfExportFile
{


    /**
     * 导出excel
     * @param string $filename 文件名
     * @param array  $titles excel 列标题
     * @param array  $datalist excel 内容
     * @throws Exception
     * @throws \PhpOffice\PhpSpreadsheet\Writer\Exception
     */
    public static function textarea_to_word(string $save_url, string $html, int $auto_export = 0) {
        if (!class_exists(TemplateProcessor::class)) {
            throw new Exception("请先执行 'composer require phpoffice/phpword'");
        }
        $save_url = trim($save_url,'/');
        
        // 预处理 HTML，修复图片高度问题
        $html = preg_replace_callback('/<img([^>]*)style=[\'"]([^\'"]*)[\'"]([^>]*)>/i', function($matches) {
            $beforeStyle = $matches[1];
            $style = $matches[2];
            $afterStyle = $matches[3];
            
            // 从样式中提取宽度和高度
            preg_match('/width\s*:\s*(\d+)px/i', $style, $widthMatch);
            preg_match('/height\s*:\s*(\d+)px/i', $style, $heightMatch);
            
            $width = $widthMatch[1] ?? '';
            $height = $heightMatch[1] ?? '';
            
            // 如果找到宽度和高度，添加到 img 标签属性中
            if ($width && $height) {
                return "<img{$beforeStyle}width=\"{$width}\" height=\"{$height}\" style=\"{$style}\"{$afterStyle}>";
            }
            
            return $matches[0];
        }, $html);

        $phpWord = new PhpWord();
        $section = $phpWord->addSection();
        
        \PhpOffice\PhpWord\Shared\Html::addHtml($section, $html);

        $objWriter = IOFactory::createWriter($phpWord, 'Word2007');
        
        if ($auto_export == 1) {
            // 方式1：保存到服务器文件
            $full_path = './'.$save_url;
            $dir = dirname($full_path);
            if (!is_dir($dir)) {
                mkdir($dir, 0755, true);
            }
            $objWriter->save($full_path);
            return true;
        } else {
            // 方式2：直接输出到浏览器下载
            $filename = basename($save_url);
            if (empty($filename) || $filename === $save_url) {
                $filename = 'document_' . date('YmdHis') . '.docx';
            }
            
            // 设置 HTTP headers 用于下载
            header('Content-Type: application/vnd.openxmlformats-officedocument.wordprocessingml.document');
            header('Content-Disposition: attachment; filename="' . $filename . '"');
            header('Content-Transfer-Encoding: binary');
            header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
            header('Expires: 0');
            header('Pragma: public');
            
            // 直接输出到浏览器
            $objWriter->save('php://output');
            
            // 结束脚本执行，避免额外输出
            exit;
        }
    }

    /**获取xlsx文件中的某些内容
     * 传入一个一维数组，如：['A1','B1']
     * 返回一个一位数组的值：
     * [
     *     'A1' => '内容',
     *     'B1' => '内容',
     * ]
     */
    public static function get_content($file_path, $path_data = []){
        if (!class_exists(Spreadsheet::class)) {
            throw  new  Exception("请先执行 'composer require phpoffice/phpspreadsheet'");
        }
        // 方法1：尝试标准读取
        $inputFileName = trim($file_path, '/');
        try {
            $spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load(trim($file_path,'/'));

            
            
            
            // $reader = \PhpOffice\PhpSpreadsheet\IOFactory::createReaderForFile($inputFileName);
            // $reader->setReadDataOnly(true);
            // $reader->setLoadSheetsOnly([0]); // 只加载第一个工作表
            
            // $spreadsheet = $reader->load($inputFileName);
        } catch (\Exception $firstException) {
            // 方法1失败，尝试方法2：忽略 XML 错误
            $reader = \PhpOffice\PhpSpreadsheet\IOFactory::createReader('Xlsx');
            $reader->setReadDataOnly(true);
            // $reader->setLoadSheetsOnly([0]);
            
            // 清除之前的 XML 错误
            libxml_clear_errors();
            
            $spreadsheet = $reader->load($inputFileName);
        }

        // 获取第一个工作表（默认）
        // $worksheet = $spreadsheet->getActiveSheet();
        //第一个工作表
        // halt(123);
        $worksheet = $spreadsheet->getSheet(0);
        $data = [];
        foreach ($path_data as $key => $value) {
            $value_arr = explode(',',$value);
            $str = '';
            foreach ($value_arr as $key_arr => $value_arr_value) {
                // $str .= $worksheet->getCell($value_arr_value)->getCalculatedValue();
                $cell = $worksheet->getCell($value_arr_value);
                $cellValue = $cell->getCalculatedValue();
                
                // 处理日期
                if (\PhpOffice\PhpSpreadsheet\Shared\Date::isDateTime($cell)) {
                    try {
                        $dateValue = \PhpOffice\PhpSpreadsheet\Shared\Date::excelToDateTimeObject($cellValue);
                        $str .= $dateValue->format('Y-m-d');
                    } catch (\Exception $e) {
                        $str .= $cellValue;
                    }
                } else {
                    $str .= $cellValue;
                }
            }
            $data[$value] = $str;
        }
        // 获取单元格值
        return ['',$data];
    }
    

    /**修改xlsx文件
     * 
     */
    public static function edit_excel($file_path, $new_path, $new_file_name, $string_arr = [], $image_arr = [])
    {
        if (!class_exists(Spreadsheet::class)) {
            throw  new  Exception("请先执行 'composer require phpoffice/phpspreadsheet'");
        }
        $new_path = trim($new_path,'/');
        // 方法1：尝试标准读取
        $inputFileName = trim($file_path, '/');
        try {
            $spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load(trim($file_path,'/'));
            
            
            // $reader = \PhpOffice\PhpSpreadsheet\IOFactory::createReaderForFile($inputFileName);
            // $reader->setReadDataOnly(true);
            // $reader->setLoadSheetsOnly([0]); // 只加载第一个工作表
            
            // $spreadsheet = $reader->load($inputFileName);
        } catch (\Exception $firstException) {
            // 方法1失败，尝试方法2：忽略 XML 错误
            $reader = \PhpOffice\PhpSpreadsheet\IOFactory::createReader('Xlsx');
            $reader->setReadDataOnly(true);
            $reader->setLoadSheetsOnly([0]);
            
            // 清除之前的 XML 错误
            libxml_clear_errors();
            
            $spreadsheet = $reader->load($inputFileName);
        }
        // $sheet = $spreadsheet->getActiveSheet();
        $sheet = $spreadsheet->getSheet(0);
        foreach ($string_arr as $key => $value) {
            $sheet->setCellValue($value['xy'], $value['string']);
            if (isset($value['url'])) {
                $sheet->getCell($value['xy'])->getHyperlink()->setUrl($value['url']);
            }
            if (isset($value['tip'])) {
                $sheet->getCell($value['xy'])->getHyperlink()->setTooltip($value['tip']);
            }
        }
        // ['xy' => 'A1','name' => '二维码','path' => $qrcpde_url,'description' => '二维码提示','height' => 100,'with' => 100],
        foreach ($image_arr as $kkk => $vvvv) {
            if (!file_exists(trim($vvvv['path'],'/')) ) {
                continue;
            }
            if ( empty($vvvv['xy'])) {
                continue;
            }
            $drawing = new \PhpOffice\PhpSpreadsheet\Worksheet\Drawing();
            $drawing->setName($vvvv['name'] ?? '图片');
            $drawing->setDescription($vvvv['description'] ?? '图片描述');
            $drawing->setPath(trim($vvvv['path'],'/')); // 图片路径
            $drawing->setHeight($vvvv['height'] ?? 200); // 设置图片高度
            $drawing->setWidth($vvvv['with'] ?? 200); // 设置图片宽度
            // 设置图片位置（例如放在D2单元格）
            $drawing->setCoordinates($vvvv['xy']);
            // 可选：设置偏移量（像素）
            $drawing->setOffsetX($vvvv['x'] ?? 0);
            $drawing->setOffsetY($vvvv['y'] ?? 0);
            // 将图片添加到工作表
            $drawing->setWorksheet($sheet);
        }
        
        $writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Xlsx');
        // 确保目录存在
        $directory = dirname('.' . DIRECTORY_SEPARATOR . $new_path . '/' . $new_file_name . '.xlsx');
        if (!is_dir($directory)) {
            mkdir($directory, 0755, true);
        }
        $writer->save($new_path . '/' . $new_file_name . '.xlsx');
        return ['', '/'.$new_path . '/' . $new_file_name . '.xlsx'];
    }
}
